package com.itboye.sunsun.web.ui;

import java.io.FileNotFoundException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.itboye.luntan.web.CustomDialog;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.person.ui.PersonSettingActivity;
import com.itboye.sunsun.product.center.DownPicUtil;
import com.itboye.sunsun.product.center.ProcdeuWebView;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.utils.CameraPopupWindow;
import com.itboye.sunsunhome.R;
import com.itboye.sunsunhome.util.Byalert;

@SuppressLint("SetJavaScriptEnabled")
public class PricentActivity extends BaseActivity {

	private WebView contentWebView = null;
	private ArrayAdapter<String> adapter;
	private CustomDialog mCustomDialog;
	String picFile;
	String urls;
	String name;
	TextView title;
	@SuppressLint("InlinedApi")
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.activity_web);
		contentWebView = (WebView) findViewById(R.id.webview);
		// 启用javascript
		contentWebView.getSettings().setJavaScriptEnabled(true);
		
		urls=getIntent().getStringExtra("url");
		name=getIntent().getStringExtra("titlt");
		title.setText("产品信息");
		// 随便找了个带图片的网站
		contentWebView
				.loadUrl(urls);
		// 添加js交互接口类，并起别名 imagelistner
		contentWebView.addJavascriptInterface(new JavascriptInterface(this),
				"imagelistner");
		contentWebView.setWebViewClient(new MyWebViewClient());

	}

	// 注入js函数监听
	private void addImageClickListner() {
		// 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，在还是执行的时候调用本地接口传递url过去
		contentWebView.loadUrl("javascript:(function(){"
				+ "var objs = document.getElementsByTagName(\"img\"); "
				+ "for(var i=0;i<objs.length;i++)  " + "{"
				+ "    objs[i].onclick=function()  " + "    {  "
				+ "        window.imagelistner.openImage(this.src);  "
				+ "    }  " + "}" + "})()");
	}

	// js通信接口
	public class JavascriptInterface {

		public Context context;

		public JavascriptInterface(Context context) {
			this.context = context;
		}

		public void openImage(String img) {
			System.out.println(img);

	

			showDialog(img);
			
			System.out.println(img);

		}
	}
	 private void  showDialog(final String url) {
	    	
	    	adapter = new ArrayAdapter<String>(this,R.layout.item_dialog);  
	        adapter.add("保存到手机"); 
	        adapter.add("查看大图");
	        adapter.add("取消");
	    	
	    	mCustomDialog = new CustomDialog(this, R.layout.custom_dialog) {
				
				@Override
				public void initViews() {
					// 初始CustomDialog化控件
					ListView mListView = (ListView) findViewById(R.id.lv_dialog);
			        mListView.setAdapter(adapter); 
			        mListView.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
							// 点击事件
							switch (position) {
							case 0:
								
								
								// 下载图片到本地
								DownPicUtil
										.downPic(
												url,
												new DownPicUtil.DownFinishListener() {

													@Override
													public void getDownPath(
															String s) {
													Toast.makeText(App.ctx, "下载完成", 0).show();
														Message msg = Message
																.obtain();
														msg.obj = s;
														handler.sendMessage(msg);
													}
												});
								closeDialog();
								
								break;
							case 1:
								
									Intent intent = new Intent();
									intent.putExtra("image", url);
									System.out.println(">>>>>>>>>>>>>>>"+url);
									intent.setClass(PricentActivity.this, ImageShower.class);
									startActivity(intent);
								
								break;
								
							case 2:
								closeDialog();
								break;
							}
							
						}
					});
				}
			};
			mCustomDialog.show();
	    }

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			 picFile = (String) msg.obj;
			String[] split = picFile.split("/");
			String fileName = split[split.length - 1];
			try {
				MediaStore.Images.Media.insertImage(getApplicationContext()
						.getContentResolver(), picFile, fileName, null);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			// 最后通知图库更新
			getApplicationContext().sendBroadcast(
					new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
							.parse("file://" + picFile)));
			Toast.makeText(App.ctx, "图片保存成功"+picFile, 0).show();
			// Toast.makeText(context, "图片保存图库成功"+picFile,
			// Toast.LENGTH_LONG).show();
		}
	};

	// 监听
	private class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {

			return super.shouldOverrideUrlLoading(view, url);
		}

		@Override
		public void onPageFinished(WebView view, String url) {

			view.getSettings().setJavaScriptEnabled(true);

			super.onPageFinished(view, url);
			// html加载完成之后，添加监听图片的点击js函数
			addImageClickListner();

		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			view.getSettings().setJavaScriptEnabled(true);

			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {

			super.onReceivedError(view, errorCode, description, failingUrl);

		}
	}

}